#!/bin/bash

# EMS开发环境部署脚本
# 用途: 快速搭建开发环境，安装依赖并构建项目

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查系统依赖
check_system_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        log_info "检测到Linux系统"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        log_info "检测到macOS系统"
    else
        log_error "不支持的操作系统: $OSTYPE"
        exit 1
    fi
    
    # 检查编译器
    if command -v g++ &> /dev/null; then
        GCC_VERSION=$(g++ --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -1)
        log_info "找到g++: $GCC_VERSION"
    elif command -v clang++ &> /dev/null; then
        CLANG_VERSION=$(clang++ --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -1)
        log_info "找到clang++: $CLANG_VERSION"
    else
        log_error "未找到C++编译器 (g++或clang++)"
        exit 1
    fi
    
    # 检查CMake
    if ! command -v cmake &> /dev/null; then
        log_error "CMake未安装"
        if [[ "$OS" == "macos" ]]; then
            log_info "请运行: brew install cmake"
        elif [[ "$OS" == "linux" ]]; then
            log_info "请运行: sudo apt-get install cmake (Ubuntu/Debian) 或 sudo yum install cmake (CentOS/RHEL)"
        fi
        exit 1
    fi
    
    CMAKE_VERSION=$(cmake --version | head -n1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
    log_info "找到CMake: $CMAKE_VERSION"
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        log_error "Node.js未安装"
        log_info "请安装Node.js >= 16.0: https://nodejs.org/"
        exit 1
    fi
    
    NODE_VERSION=$(node --version)
    log_info "找到Node.js: $NODE_VERSION"
    
    # 检查Python3 (用于资源嵌入脚本)
    if ! command -v python3 &> /dev/null; then
        log_error "Python3未安装"
        exit 1
    fi
    
    PYTHON_VERSION=$(python3 --version)
    log_info "找到Python3: $PYTHON_VERSION"
    
    log_success "系统依赖检查完成"
}

# 安装项目依赖
install_project_dependencies() {
    log_info "安装项目依赖..."
    
    # 创建第三方库目录
    mkdir -p "$PROJECT_ROOT/third_party"
    cd "$PROJECT_ROOT/third_party"
    
    # 检查并下载nlohmann/json
    if [ ! -f "json/nlohmann/json.hpp" ]; then
        log_info "下载nlohmann/json..."
        mkdir -p json/nlohmann
        curl -L "https://github.com/nlohmann/json/releases/download/v3.11.2/json.hpp" \
            -o json/nlohmann/json.hpp
        log_success "nlohmann/json下载完成"
    else
        log_info "nlohmann/json已存在"
    fi
    
    # 检查并安装libmodbus (如果需要)
    if [ ! -d "modbus" ] && [ "$INSTALL_MODBUS" = "true" ]; then
        log_info "下载libmodbus..."
        git clone https://github.com/stephane/libmodbus.git modbus
        cd modbus
        ./autogen.sh
        ./configure --prefix="$PROJECT_ROOT/third_party/modbus/install"
        make && make install
        cd ..
        log_success "libmodbus安装完成"
    fi
    
    # 检查并安装Paho MQTT (如果需要)
    if [ ! -d "mqtt" ] && [ "$INSTALL_MQTT" = "true" ]; then
        log_info "下载Paho MQTT C++..."
        git clone https://github.com/eclipse/paho.mqtt.cpp.git mqtt
        cd mqtt
        cmake -Bbuild -H. -DPAHO_BUILD_STATIC=ON -DPAHO_BUILD_SHARED=OFF
        cmake --build build/
        cd ..
        log_success "Paho MQTT安装完成"
    fi
}

# 构建C++项目
build_cpp_project() {
    log_info "构建C++项目..."
    
    cd "$PROJECT_ROOT"
    
    # 运行现有的构建脚本
    if [ -f "scripts/build.sh" ]; then
        log_info "使用现有构建脚本..."
        ./scripts/build.sh
    else
        # 手动构建
        mkdir -p build
        cd build
        cmake ..
        make -j$(nproc 2>/dev/null || echo 4)
        cd ..
    fi
    
    log_success "C++项目构建完成"
}

# 构建Web前端
build_web_frontend() {
    log_info "构建Web前端..."
    
    if [ -f "$PROJECT_ROOT/scripts/build-web.sh" ]; then
        "$PROJECT_ROOT/scripts/build-web.sh"
    else
        log_warning "未找到Web构建脚本"
    fi
}

# 生成配置文件模板
generate_config_templates() {
    log_info "生成配置文件模板..."
    
    CONFIG_DIR="$PROJECT_ROOT/config"
    mkdir -p "$CONFIG_DIR"
    
    # 如果配置文件不存在则创建模板
    if [ ! -f "$CONFIG_DIR/system.json" ]; then
        cat > "$CONFIG_DIR/system.json" << 'EOF'
{
    "basic": {
        "system_name": "EMS 能源管理系统",
        "device_id": "ems-gateway-001",
        "work_mode": "gateway",
        "listen_port": 8080,
        "api_port": 8081,
        "websocket_port": 8082
    },
    "collection": {
        "interval": 30,
        "timeout": 5000,
        "retry_count": 3,
        "max_concurrent": 10,
        "auto_reconnect": true,
        "enable_cache": true,
        "cache_size": 100,
        "enable_compression": false
    },
    "logging": {
        "level": "info",
        "file_path": "./logs/system.log",
        "max_file_size": 10,
        "max_files": 5,
        "console_output": true,
        "enable_remote": false,
        "remote_host": "",
        "remote_port": 514
    },
    "security": {
        "enable_auth": false,
        "username": "admin",
        "password": "admin123",
        "session_timeout": 60,
        "allow_ips": "0.0.0.0/0",
        "enable_https": false,
        "cert_file": "",
        "key_file": "",
        "https_port": 8443
    }
}
EOF
        log_success "生成system.json模板"
    fi
    
    if [ ! -f "$CONFIG_DIR/mqtt.json" ]; then
        cat > "$CONFIG_DIR/mqtt.json" << 'EOF'
{
    "broker": {
        "host": "192.168.1.100",
        "port": 8883,
        "use_tls": true,
        "ca_file": "",
        "cert_file": "",
        "key_file": ""
    },
    "client": {
        "device_sn": "ems-gateway-001",
        "device_type": "100",
        "keep_alive": 300,
        "clean_session": true,
        "qos": 1
    },
    "topics": {
        "data_upload": "up/gateway/report/data",
        "alarm_upload": "up/gateway/report/alarm",
        "login": "up/gateway/login",
        "command_response": "up/gateway/command/response"
    }
}
EOF
        log_success "生成mqtt.json模板"
    fi

    if [ ! -f "$CONFIG_DIR/mqtt.conf" ]; then
        if [ -f "$CONFIG_DIR/mqtt.template.conf" ]; then
            cp "$CONFIG_DIR/mqtt.template.conf" "$CONFIG_DIR/mqtt.conf"
            log_success "从模板复制 mqtt.conf"
        else
            cat > "$CONFIG_DIR/mqtt.conf" << 'EOF'
{
  "broker": {
    "host": "127.0.0.1",
    "port": 1883,
    "use_tls": false,
    "ca_file": "",
    "cert_file": "",
    "key_file": ""
  },
  "client": {
    "device_sn": "",
    "device_type": "",
    "username": "",
    "password": "",
    "keep_alive": 60,
    "clean_session": true,
    "qos": 1,
    "retained": false
  },
  "topics": {
    "topic_prefix": "/ext/${deviceSn}/register",
    "data_upload": "up/gateway/report/data",
    "alarm_upload": "up/gateway/report/alarm",
    "alarm_clear": "up/gateway/report/alarm_clear",
    "device_sync": "up/gateway/sync/res",
    "login": "up/gateway/login",
    "command_response": "up/gateway/command/response"
  },
  "security": {
    "sign_method": "hmacsha256",
    "device_type_secret": ""
  }
}
EOF
            log_success "生成mqtt.conf模板"
        fi
    fi

    if [ ! -f "$CONFIG_DIR/devices.json" ]; then
        if [ -f "$CONFIG_DIR/devices.template.json" ]; then
            cp "$CONFIG_DIR/devices.template.json" "$CONFIG_DIR/devices.json"
            log_success "从模板复制 devices.json"
        else
            cat > "$CONFIG_DIR/devices.json" << 'EOF'
{
    "devices": [
        {
            "id": 1,
            "name": "测试设备1",
            "protocol": "modbus_tcp",
            "address": "192.168.1.200",
            "port": 502,
            "slave_id": 1,
            "timeout": 5000,
            "poll_interval": 1000,
            "enabled": true,
            "description": "Modbus TCP测试设备"
        }
    ]
}
EOF
            log_success "生成devices.json模板"
        fi
    fi
}

# 设置权限
setup_permissions() {
    log_info "设置文件权限..."
    
    # 确保脚本可执行
    chmod +x "$PROJECT_ROOT"/scripts/*.sh
    chmod +x "$PROJECT_ROOT"/scripts/*.py
    
    # 确保可执行文件有执行权限
    if [ -f "$PROJECT_ROOT/build/ems-cpp-v1" ]; then
        chmod +x "$PROJECT_ROOT/build/ems-cpp-v1"
    fi
    
    # 创建日志目录
    mkdir -p "$PROJECT_ROOT/logs"
    
    log_success "权限设置完成"
}

# 运行测试
run_tests() {
    if [ "$SKIP_TESTS" = "true" ]; then
        log_warning "跳过测试"
        return
    fi
    
    log_info "运行测试..."
    
    if [ -d "$PROJECT_ROOT/tests" ] && [ -f "$PROJECT_ROOT/build/test_runner" ]; then
        cd "$PROJECT_ROOT"
        ./build/test_runner
        log_success "测试通过"
    else
        log_warning "未找到测试程序，跳过测试"
    fi
}

# 显示部署完成信息
show_completion_info() {
    log_success "EMS开发环境部署完成！"
    echo
    log_info "项目目录: $PROJECT_ROOT"
    log_info "C++可执行文件: $PROJECT_ROOT/build/ems-cpp-v1"
    log_info "Web构建产物: $PROJECT_ROOT/build/web/"
    log_info "配置文件目录: $PROJECT_ROOT/config/"
    echo
    log_info "启动命令:"
    log_info "  cd $PROJECT_ROOT"
    log_info "  ./build/ems-cpp-v1"
    echo
    log_info "Web管理界面: http://localhost:8080"
    log_info "API接口: http://localhost:8081"
    echo
    log_info "其他有用命令:"
    log_info "  ./scripts/build.sh          # 重新构建C++项目"
    log_info "  ./scripts/build-web.sh      # 重新构建Web前端"
    log_info "  ./scripts/deploy-dev.sh     # 重新部署开发环境"
}

# 主函数
main() {
    log_info "开始部署EMS开发环境..."
    log_info "项目根目录: $PROJECT_ROOT"
    
    check_system_dependencies
    install_project_dependencies
    build_cpp_project
    build_web_frontend
    generate_config_templates
    setup_permissions
    run_tests
    show_completion_info
}

# 处理命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-tests)
            SKIP_TESTS=true
            shift
            ;;
        --install-modbus)
            INSTALL_MODBUS=true
            shift
            ;;
        --install-mqtt)
            INSTALL_MQTT=true
            shift
            ;;
        --help|-h)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  --skip-tests       跳过测试运行"
            echo "  --install-modbus   安装libmodbus库"
            echo "  --install-mqtt     安装Paho MQTT库"
            echo "  --help, -h         显示此帮助信息"
            exit 0
            ;;
        *)
            log_error "未知选项: $1"
            exit 1
            ;;
    esac
done

main